package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String url = request.getRequestURL().toString();
        log.info("请求url:{}",url);
        if(url.contains("login")){
            log.info("is login, release");
            filterChain.doFilter(request,response);
            return;
        }
        String jwt = request.getHeader("token");
        if(StringUtils.isEmpty(jwt)){
            log.info("token is empty");
            Result error = Result.error("NOT_LOGIN");
            String jsonError = JSONObject.toJSONString(error);
            response.getWriter().write(jsonError);
            return;
        }
        try{
            Claims claims = JwtUtils.parseJWT(jwt);

        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌错误");
            Result error = Result.error("NOT_LOGIN");
            String jsonError = JSONObject.toJSONString(error);
            response.getWriter().write(jsonError);
            return;
        }
        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);
    }
}
